package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.apUser.dtos.LoginDto;
import com.heima.model.apUser.pojos.ApUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * 用户业务逻辑处理层实现类
 *
 * @author 11494
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/2/29 19:51:18
 */
@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 用户数据访问层
     *
     * @author 11494
     * @version 1.0
     * @project heima-leadnews
     * @date 2024/2/29 19:48:39
     */
    @Override
    public ResponseResult loginAuth(LoginDto loginDto) {
        //参数校验
        if (loginDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //核心代码输出
        //先判断是否为游客登录
        if (loginDto.getPassword() == null && loginDto.getPhone() == null) {
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        //判断用户

        LambdaQueryWrapper<ApUser> wrapper = Wrappers.<ApUser>lambdaQuery().eq(loginDto.getPhone() != null, ApUser::getPhone, loginDto.getPhone());
        ApUser user = getOne(wrapper);
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String s = DigestUtils.md5DigestAsHex((loginDto.getPassword() + user.getSalt()).getBytes());
        if (!s.equals(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //结果封装
        HashMap<String, Object> map = new HashMap<>();
        String token = AppJwtUtil.getToken(user.getId().longValue());
        map.put("token", token);
        map.put("user", user);
        return ResponseResult.okResult(map);
    }
}
